//
//  DataManager.m
//  music
//
//  Created by 赵鹏宇 on 16/4/8.
//  Copyright © 2016年 赵鹏宇. All rights reserved.
//

#import "DataManager.h"

@implementation DataManager

- (NSString *)computeDataWithType:(NSString *)type Length:(int)len Mode:(NSString *)mode Data:(NSString *)color
{
    NSString *start = @"01";
    NSString *length = [NSString stringWithFormat:@"%04x",len];
    if (mode) {
        color = [NSString stringWithFormat:@"%@%@",mode,color];
    }
    if ([mode isEqualToString:@"0002"]||[mode isEqualToString:@"0005"]||[mode isEqualToString:@"0006"]) {
        length =[NSString stringWithFormat:@"%04x",(int)color.length/2];
    }
    NSString *crc = [self getCRCWithType:type Length:length Data:color];
    NSString *end = @"03";
    NSString *data = [NSString stringWithFormat:@"%@%@%@%@",type,length,crc,color];
    NSArray *arr = [self getSubstringByString:data];
    NSMutableArray *marr = [NSMutableArray array];
    for (int i = 0;i<arr.count;i++) {
        NSString *str = arr[i];
        if ([[str substringToIndex:1] isEqualToString:@"0"]) {
            [marr addObject:@"02"];
            [marr addObject:[self pinxCreator:str withPinv:@"10"]];
        }else{
            [marr addObject:str];
        }
    }
    NSString *result = start;
    for (NSString *str in marr) {
        result = [NSString stringWithFormat:@"%@%@",result,str];
    }
    result = [NSString stringWithFormat:@"%@%@",result,end];
    return result;
}

- (NSString *)pinxCreator:(NSString *)pan withPinv:(NSString *)pinv
{
    unsigned long panchar = strtoul([pan UTF8String],0,16);
    unsigned long pinvchar = strtoul([pinv UTF8String],0,16);
    NSString *temp = [NSString stringWithFormat:@"%02lx",panchar^pinvchar];
    return temp;
}

- (NSString *)getCRCWithType:(NSString *)type Length:(NSString *)length Data:(NSString *)data
{
    NSString *result = @"00";
    NSArray *arr = [self getSubstringByString:type];
    for (NSString *str in arr) {
        result = [self pinxCreator:result withPinv:str];
    }
    arr = [self getSubstringByString:length];
    for (NSString *str in arr) {
        result = [self pinxCreator:result withPinv:str];
    }
    arr = [self getSubstringByString:data];
    for (NSString *str in arr) {
        result = [self pinxCreator:result withPinv:str];
    }
    return result;
}

- (NSArray *)getSubstringByString:(NSString *)superstring
{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i=0; i<superstring.length; i+=2) {
        NSString *str = [superstring substringWithRange:NSMakeRange(i, 2)];
        [arr addObject:str];
    }
    return arr;
}

@end
